// 登录模块仓库
import { defineStore } from 'pinia'

export const useMusicStore = defineStore(
  'music',
  () => {
    const state = reactive({
      defaultDir: 'E:\\music',
      musicList: [],
      currentPlay: {
        isPlay: false,
        id: '',
        name: '',
        path: '',
        duration: '',
        extension: ''
      }
    })
    const { musicList, currentPlay } = toRefs(state)

    //扫描默认文件地址下的音乐列表
    const loadDefaultAudioFiles = async () => {
      if (!state.defaultDir) return
      let error = ''
      try {
        //扫描选定目录中的音频文件
        const result = await window.api.scanAudioFiles(state.defaultDir)

        if (result.success) {
          let timeStamp = new Date().getTime()
          state.musicList = result.files
          state.musicList.forEach((item, index) => {
            item.time = timeStamp + index
          })
        } else {
          error = `扫描失败: ${result.error}`
        }
      } catch (err) {
        error = `发生错误: ${err.message}`
      }
    }

    const updateList = (list) => {
      state.musicList = list
    }

    //更新当前播放歌曲
    const updateCurrentPlay = (val) => {
      state.currentPlay = val
    }

    //更新歌曲播放时间
    const updateCurrentPlayTime = (val) => {
      state.currentPlay.currentTime = val
    }

    return {
      musicList,
      currentPlay,
      loadDefaultAudioFiles,
      updateList,
      updateCurrentPlay,
      updateCurrentPlayTime
    }
  },
  { persist: true }
) // 开启持久化
